package com.axonactive.yolo.monitor;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.axonactive.yolo.domain.Country;
import com.axonactive.yolo.service.interfaces.CountryService;
import com.axonactive.yolo.service.internal.JSONProcessor;
import com.axonactive.yolo.util.IOUtil;


public class CheckUpdateCurrency {
	private final static Logger LOGGER = Logger
			.getLogger(CheckUpdateCurrency.class);
	public static boolean ISFINISHED=true;
	private final String url="http://restcountries.eu/rest/v1/all";
	
	@Autowired
	private CountryService countryService;
	/**
	 * detect the country data is updated.If it detect the change, update the new value into db
	 * @return true if all operations are success, other return false;
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public boolean run() throws ClientProtocolException, IOException {
		ISFINISHED=false;
		LOGGER.info("Check update currency IN");
		//call to server
		String response=IOUtil.callToServer(url);
		//read response and convert it to list of country
		List<Country> countries=JSONProcessor.getCountries(response);
		//compare it with exist db
		boolean rs=compareWithExistedDB(countries);
		
		LOGGER.info("Check update currency OUT");
		ISFINISHED=true;
		return rs;
	}

	//get list of existed country in db
	//for each country in returned response from server
	//	+	if country isn't exist in db, let insert it into db
	//	+	if country is exist in db
	//		+ if it's difference, update the new country
	//		+ if it's the same, ignore
	public boolean compareWithExistedDB(List<Country> countries) {
		List<Country> existDB=countryService.findAll();
		int index=-1;
		for (Iterator iterator = countries.iterator(); iterator.hasNext();) {
			Country country = (Country) iterator.next();
			index=hasContainCountry(existDB, country);
			if (index==-1)
			{//country isn't exist in db, 
				LOGGER.info("create new row in db: "+country.getCountryName()+"-"+country.getCountryCode());
				countryService.create(country);
			}
			else
			{
				if (country.getCurrencyCode().equals(existDB.get(index).getCurrencyCode()))
				{
//					LOGGER.info("country existed in db: "+country.getCountryName()+"-"+country.getCountryCode());
					continue;
				}
				else 
				{
					LOGGER.info("insert into db: "+country.getCountryName()+"-"+country.getCountryCode());
					existDB.get(index).setCurrencyCode(country.getCurrencyCode());
					countryService.update(existDB.get(index));
				}
			}
		}
		return true;
	}
	
	public int hasContainCountry(List<Country> countries,Country country)
	{
		 for (int i = 0; i < countries.size(); i++) {
			if (countries.get(i).getCountryCode().equals(country.getCountryCode()))
					return i;
		}
		 return -1;
	}
	
	public CountryService injectService(CountryService countryService)
	{
		this.countryService=countryService;
		return this.countryService;
	}
}
